﻿using BCCommon;
using BCCommon.Enums;
using BCData.Trading.Enquiry.SaleEnquiry;
using BCDto.Trading.Enquiry.SaleEnquiry;
using BCEntity.Trading.Enquiry.SaleEnquiry;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCService.Trading.SaleShoppingCart;
using BCService.Trading.SaleGoods.SaleGoods;
using BCService.Sim.Admin.StaffOrganizationMappingRecord;
using BCDto.Sim.Admin.StaffOrganizationMappingRecord;
using BCService.Trading.Enquiry.SaleEnquiryChecklist;
using BCDto.Trading.Enquiry.SaleEnquiryChecklist;
using BCDto.Sim.Admin.Admin;

namespace BCService.Trading.Enquiry.SaleEnquiry
{
    public class SaleEnquiryService : ISaleEnquiryService
    {
        private readonly IDatabaseContext databaseContext;
        private readonly IRedisService redisService;
        private readonly ISaleEnquiryData saleEnquiryData;
        private readonly ISaleShoppingCartService saleShoppingCartService;
        private readonly ISaleGoodsService saleGoodsService;
        private readonly IStaffOrganizationMappingRecordService staffOrganizationMappingRecordService;
        private readonly ISaleEnquiryChecklistService saleEnquiryChecklistService;
        private readonly string key = string.Format("{0}", EntityNameConst.SaleEnquiryEntity);

        public SaleEnquiryService(IDatabaseContext databaseContext,
            IRedisService redisService,
            ISaleEnquiryData saleEnquiryData,
            ISaleShoppingCartService saleShoppingCartService,
            ISaleGoodsService saleGoodsService,
            IStaffOrganizationMappingRecordService staffOrganizationMappingRecordService,
            ISaleEnquiryChecklistService saleEnquiryChecklistService)
        {
            this.databaseContext = databaseContext;
            this.redisService = redisService;
            this.saleEnquiryData = saleEnquiryData;
            this.saleShoppingCartService = saleShoppingCartService;
            this.saleGoodsService = saleGoodsService;
            this.staffOrganizationMappingRecordService = staffOrganizationMappingRecordService;
            this.saleEnquiryChecklistService = saleEnquiryChecklistService;
        }

        #region 检查销售询盘是否存在
        public bool Exists(long saleEnquiryId)
        {
            return this.saleEnquiryData.Exists(saleEnquiryId).GetAwaiter().GetResult();
        }
        #endregion

        #region 添加销售询盘
        public SaleEnquiryDto Add(SaleEnquiryUserRequestDto requestDto)
        {
            //if (!requestDto.SaleShoppingCartId.HasValue && !requestDto.SaleGoodsNormId.HasValue)
            //{
            //    throw new ArgumentException("购物车Id和商品款式Id不能同时为空!");
            //}
            var entity = requestDto.As<SaleEnquiryEntity>();
            //if (requestDto.SaleShoppingCartId.HasValue)
            //{
            //    var dto = this.saleShoppingCartService.Get(requestDto.SaleShoppingCartId.Value);
            //    entity.SaleGoodsCategoryId = dto.SaleGoodsCategoryId;
            //    entity.CategoryName = dto.CategoryName;
            //    entity.SaleGoodsId = dto.SaleGoodsId;
            //    entity.GoodsName = dto.GoodsName;
            //    entity.Sku = dto.Sku;
            //    entity.SaleGoodsNormId = dto.SaleGoodsNormId;
            //    entity.NormName = dto.NormName;
            //    entity.NormNo = dto.NormNo;
            //    entity.MainImage = dto.MainImage;
            //}
            //else
            //{
            //    var dto = this.saleGoodsService.GetGoodsNorm(requestDto.SaleGoodsNormId.Value);
            //    entity.SaleGoodsCategoryId = dto.SaleGoodsCategoryId;
            //    entity.CategoryName = dto.CategoryName;
            //    entity.SaleGoodsId = dto.SaleGoodsId;
            //    entity.GoodsName = dto.GoodsName;
            //    entity.Sku = dto.Sku;
            //    entity.SaleGoodsNormId = dto.SaleGoodsNormId;
            //    entity.NormName = dto.NormName;
            //    entity.NormNo = dto.NormNo;
            //    entity.MainImage = dto.MainImage;
            //}

            var staffList = this.staffOrganizationMappingRecordService.GetJobTitleStaffList("StaffTitle_Representative_Sales");
            Random random = new Random();
            int index = random.Next(staffList.Count());
            var staff = staffList.ElementAt(index);
            if(staff == null&&staffList.Any())
            {
                staff = staffList.First();
            }
            else
            {
                staff = new StaffViewDto
                {
                    FullName = "Administrator",
                    AdminId = 1
                };
            }
            entity.ReceiptAdminName = staff.FullName;
            entity.ReceiptAdminId = staff.AdminId;
            databaseContext.BeginTransaction();
            var result = this.saleEnquiryData.Add(entity).GetAwaiter().GetResult().As<SaleEnquiryDto>();
            saleEnquiryChecklistService.Add(new SaleEnquiryChecklistRequestDto()
            {
                 SaleEnquiryId = result.SaleEnquiryId,
                 SaleGoodsNormId = requestDto.SaleEnquiryChecklist.SaleGoodsNormId
            });
            databaseContext.Commit();
            return result;
        }
        #endregion

        #region 添加销售询盘
        public SaleEnquiryDto Add(SaleEnquiryStaffRequestDto requestDto,AdminDto adminDto)
        {
            //if (!requestDto.SaleShoppingCartId.HasValue && !requestDto.SaleGoodsNormId.HasValue)
            //{
            //    throw new ArgumentException("购物车Id和商品款式Id不能同时为空!");
            //}
            var entity = requestDto.As<SaleEnquiryEntity>();
            //if (requestDto.SaleShoppingCartId.HasValue)
            //{
            //    var dto = this.saleShoppingCartService.Get(requestDto.SaleShoppingCartId.Value);
            //    entity.SaleGoodsCategoryId = dto.SaleGoodsCategoryId;
            //    entity.CategoryName = dto.CategoryName;
            //    entity.SaleGoodsId = dto.SaleGoodsId;
            //    entity.GoodsName = dto.GoodsName;
            //    entity.Sku = dto.Sku;
            //    entity.SaleGoodsNormId = dto.SaleGoodsNormId;
            //    entity.NormName = dto.NormName;
            //    entity.NormNo = dto.NormNo;
            //    entity.MainImage = dto.MainImage;
            //}
            //else
            //{
            //    var dto = this.saleGoodsService.GetGoodsNorm(requestDto.SaleGoodsNormId.Value);
            //    entity.SaleGoodsCategoryId = dto.SaleGoodsCategoryId;
            //    entity.CategoryName = dto.CategoryName;
            //    entity.SaleGoodsId = dto.SaleGoodsId;
            //    entity.GoodsName = dto.GoodsName;
            //    entity.Sku = dto.Sku;
            //    entity.SaleGoodsNormId = dto.SaleGoodsNormId;
            //    entity.NormName = dto.NormName;
            //    entity.NormNo = dto.NormNo;
            //    entity.MainImage = dto.MainImage;
            //}
            entity.ReceiptAdminName = adminDto.FullName;
            entity.ReceiptAdminId = adminDto.AdminId;

            return this.saleEnquiryData.Add(entity).GetAwaiter().GetResult().As<SaleEnquiryDto>();
        }
        #endregion

        #region 修改销售询盘
        public SaleEnquiryDto Update(SaleEnquiryPutDto putDto)
        {
            if (!this.Exists(putDto.SaleEnquiryId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            var entity = putDto.As<SaleEnquiryEntity>();

            var result = this.saleEnquiryData.Update(entity).GetAwaiter().GetResult().As<SaleEnquiryDto>();
            string cacheKey = this.redisService.GetKey(key, entity.SaleEnquiryId);
            this.redisService.DeleteAsync(cacheKey);
            return result;
        }
        #endregion

        #region 删除销售询盘
        public bool Delete(long saleEnquiryId)
        {
            if (!this.Exists(saleEnquiryId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            databaseContext.BeginTransaction();
            var result = this.saleEnquiryData.Delete(saleEnquiryId).GetAwaiter().GetResult();
            this.saleEnquiryChecklistService.DeleteEnquiry(saleEnquiryId);
            databaseContext.Commit();
            string cacheKey = this.redisService.GetKey(key, saleEnquiryId);
            this.redisService.DeleteAsync(cacheKey);
            return result;
        }
        #endregion

        #region 获取销售询盘
        public SaleEnquiryDto Get(long saleEnquiryId)
        {
            string cacheKey = this.redisService.GetKey(key, saleEnquiryId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.saleEnquiryData.GetEntity(saleEnquiryId).GetAwaiter().GetResult();
                return data;
            }, TimeSpan.FromMinutes(30));
            return result.As<SaleEnquiryDto>();
        }
        #endregion
        
        #region 获取销售询盘分页
        public PageableList<SaleEnquiryDto> Query(long? adminId, string userName, string phone, string companyName, string weChatNo, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize, AdminDto adminDto)
        {
            if (adminDto.JobDutyKey != "StaffTitle_Director_Sales") {
                adminId = adminDto.AdminId;
            }
            
            
            string cacheKey = this.redisService.GetKey(key, adminId, userName, phone, companyName, weChatNo, start, end, sortName, ascending, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.saleEnquiryData.Query(adminId,userName,phone,companyName,weChatNo,  start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
                return new PageableList<SaleEnquiryDto>
                {
                    Count = data.Item2,
                    Items = data.Item1.As<IEnumerable<SaleEnquiryDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now
                };
            }, TimeSpan.FromMinutes(30));

            return result;
        }
        public PageableList<SaleEnquiryDto> Query(long userId, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key,userId, start, end, sortName, ascending, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.saleEnquiryData.Query(userId, start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
                return new PageableList<SaleEnquiryDto>
                {
                    Count = data.Item2,
                    Items = data.Item1.As<IEnumerable<SaleEnquiryDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now
                };
            }, TimeSpan.FromMinutes(30));

            return result;
        }
        #endregion
    }
}